#!/usr/bin/env zsh
# koushare monitor

source ./config.zsh

start_timestamp=$(date +%s)

MONITOR_FILE="koushare.monitor.$start_timestamp.log"
MONITOR_FILE="${INFO_DIR}koushare.monitor.$start_timestamp.log"

PAGELIVE_JSON="${INFO_DIR}pagelive.$start_timestamp.json"
PAGELIVE_FIX_JSON="${INFO_DIR}pagelive.$start_timestamp.fix.json"
PAGELIVE_STRIP_JSON="${INFO_DIR}pagelive.$start_timestamp.fix.strip.json"

mkdir -p $INFO_DIR $RECORD_DIR $DB_DIR $LOG_DIR

echo "[I]: Start on: $start_timestamp"
echo "[I]: Monitor: $MONITOR_FILE"
echo "[I]: JSON: $PAGELIVE_STRIP_JSON"
echo "[I]: DB: $DB_FILE"

header_content="Content-Type: application/json"
header_accept="Accept: application/json, text/plain, */*"
header_client="Client: front_web" # essential header
header_ua="User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
curl_method="GET"

# fixed to 20, TODO: itertate all availables
pageliveapi="https://core.api.koushare.com/live/v1/live/pageLive?page=1&pageSize=20&liveStatus=1&mainClassId=0"

# query live info
pagelive_json=$(curl -X $curl_method -H "$header_content" -H "$header_accept" -H "$header_client" -H "$header_ua" --data "$id_data" "$pageliveapi" 2>/dev/null)
# [[ 1 -eq 1 ]] && { echo "PageLive json:\n$pagelive_json"; }
echo "$pagelive_json" > "${PAGELIVE_JSON}"

# remove embedded html elements from brief and schedule properties
python3 pagelivehandle.py "${PAGELIVE_JSON}" "${PAGELIVE_FIX_JSON}"
cat "${PAGELIVE_FIX_JSON}" | jq -r '[.data.list[] | select(.liveStatus == 1) | {id, userId, liveStatus, roomNo, flvurl, pushStreamKey, title}]' > "${PAGELIVE_STRIP_JSON}"

IDLIST=()

cat "${PAGELIVE_FIX_JSON}" | jq -r '.data.list[] | select(.liveStatus == 1) | {id, userId, liveStatus, roomNo, flvurl, pushStreamKey, title} | @json' | while read -r element; do
    id=$(echo "$element" | jq -r .id)
    title=$(echo "$element" | jq -r .title)
    flvurl=$(echo "$element" | jq -r .flvurl)
    pushStreamKey=$(echo "$element" | jq -r .pushStreamKey)
    fullflvurl="${flvurl}?$(echo $pushStreamKey | sed -nE 's/[^?]*\?(txSecret=.*)/\1/p')"
    # the txSecret from pagelive api is not valid, still requires a liveauthapi query
    echo -e "$id" > "$MONITOR_FILE"
    IDLIST+=("$id")
done


TODOLIST=()
# check recording status
for id in $IDLIST; do
    # check id status
    result=$(sqlite3 "$DB_FILE" <<EOF
SELECT EXISTS(SELECT 1 FROM recorded_list WHERE room_id = $id AND status >= 1);
EOF
)
    if [[ "$result" -eq 1 ]]; then
        # echo "Room ID $id has at least one record with status >= 1."
    else
        # echo "No records found for Room ID $id with status >= 1."
        TODOLIST+=("$id")
    fi
done

declare -A tasks # Associative array to track tasks and their status
declare -A results # Associative array to store exit codes

for id in $TODOLIST; do
    # process id
    ./kousharerec.zsh "$id" > "${LOG_DIR}${id}".log 2>&1  &
    pid=$! # Capture PID of the background process
    tasks[$pid]="$id" # Store the task index associated with the PID
    echo "Started task $id with PID $pid"
done

# Monitor and wait for tasks
for pid in ${(k)tasks}; do
    if wait $pid; then
        results[$pid]=0 # Success
        echo "Task ${tasks[$pid]} (PID: $pid) completed successfully."
    else
        results[$pid]=$? # Capture the exit code on failure
        echo "Task ${tasks[$pid]} (PID: $pid) failed with code ${results[$pid]}."
    fi
done

# Summary
echo "All tasks completed. Results:"
for pid in ${(k)results}; do
    echo "Task ${tasks[$pid]} (PID: $pid) -> Exit code: ${results[$pid]}"
done
